<template>
  <div class="comments-section">
    <h3>评论区</h3>
    <div v-for="item in comments" :key="item.id" class="comment-item">
      <div>
        <strong>{{ item.username }}:</strong> <span>{{ item.content }}</span>
      </div>
      <span
        v-if="item.username === commentForm.username"
        style="color: red; cursor: pointer"
        @click="del(item.id)"
      >
        删除
      </span>
    </div>
    <div>
      <el-input
        class="comment-input"
        type="textarea"
        v-model="commentForm.content"
        placeholder="请输入评论内容"
      ></el-input>
    </div>
    <el-button class="comment-button" type="primary" @click="comment"
      >评论</el-button
    >

    <el-message
      v-if="errorMessage"
      :type="'error'"
      :message="errorMessage"
    ></el-message>
  </div>
</template>  
  
<script>
import request from "@/utils/request.js"; // 确保这个文件路径正确

export default {
  name: "CommentsSection",
  data() {
    return {
      comments: [],
      pageId: "",
      commentForm: {
        content: "",
        username: "",
        userId: "",
      },
      errorMessage: "",
    };
  },
  methods: {
    generateUserId() {
      return "user_" + Math.random().toString(36).substr(2, 9);
    },
    generateUsername() {
      return "User_" + Math.random().toString(36).substr(2, 5);
    },
    del(commentId) {
      const comment = this.comments.find((c) => c.id === commentId);
      if (comment && comment.username === this.commentForm.username) {
        request
          .delete(`/comments/${commentId}`)
          .then(() => {
            this.$message.success("评论删除成功");
            this.load();
          })
          .catch((error) => {
            console.error("删除评论失败:", error);
            this.$message.error("删除评论失败");
          });
      } else {
        this.$message.error("您没有权限删除此评论");
      }
    },
    load() {
      request
        .get(`/comments/${this.pageId}`)
        .then((res) => {
          this.comments = res.data;
        })
        .catch((error) => {
          console.error("加载评论失败:", error);
        });
    },
    comment() {
      this.errorMessage = "";
      if (!this.commentForm.content.trim()) {
        this.errorMessage = "评论不能为空";
        return;
      }
      this.commentForm.username = this.generateUsername(); // 每次评论时重新生成用户名（如果需要）
      this.commentForm.userId = this.generateUserId(); // 每次评论时重新生成用户ID（如果需要）
      request
        .post(`/comments/${this.pageId}`, {
          content: this.commentForm.content,
          username: this.commentForm.username,
          userId: this.commentForm.userId,
        })
        .then(() => {
          this.$message.success("评论成功");
          this.commentForm.content = "";
          this.load();
        })
        .catch((error) => {
          console.error("提交评论失败:", error);
          this.$message.error("提交评论失败");
        });
    },
  },
  mounted() {
    // 生成唯一值
    this.pageId = "value-" + Date.now() + "-" + Math.random();
    // 将唯一值存储在 localStorage
    localStorage.setItem("pageId", this.pageId);
    this.commentForm.username = this.generateUsername();
    this.commentForm.userId = this.generateUserId();
    this.load();
  },
  created() {
    // 从 localStorage 读取唯一值（如果需要）
    const storedValue = localStorage.getItem("pageId");
    if (storedValue) {
      this.pageId = storedValue;
    }
  },
  // 如果需要，可以添加props来接收外部数据
  // props: ['initialComments', 'initialPageId']
};
</script>  
  
<style scoped lang="scss">
.comments-section {
  padding: 20px;
  height: 300px;
  margin-left: 20px;
  // 评论列表样式
  .comment-item {
    padding: 10px;
    margin-left: 10px;
  }
  .comment-input {
    margin: 15px 0;
  }
  .comment-button {
    width: 80px;
    height: 40px;
    font-size: 18px;
  }
}
</style>